//
//  LWTableBar.swift
//  微博
//
//  Created by mac on 17/5/16.
//  Copyright © 2017年 mac. All rights reserved.
//

import UIKit



//第二种方式，使用代理
//NSObjectProtocol 代理都使用弱引用，否则循环引用
/// 协议
protocol LWTableBarDelegate:NSObjectProtocol {
    
    //协议方法
    func composeBtnDidSelected()
    
    
    
}

//自定义 tabbar
class LWTableBar: UITabBar {
    
    //撰写按钮的闭包
    var composeBtnClouser:(()->())?
    
    //设置代理对象
    weak var lwDelegate: LWTableBarDelegate?
    
    //mark 懒加载
    private var composeBtn: UIButton = {
        
        let btn = UIButton()
        
        //添加点击事件
        btn.addTarget(self, action:#selector(btnClick), for: .touchUpInside)
        
        
        //设置图片
        btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal)
        
        btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .selected)
        
        //设置背景图片
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal)
        
        btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .selected)
        
        
        //设置大小
        btn.sizeToFit()
        
        return btn
        
        
    }()

    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        self .setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //添加控件
    private func setupUI(){
        
        //添加子视图控件
        addSubview(composeBtn)
        
        
    }
    
    //mark 点击事件
    func btnClick() {
        
        print("66666")
        
        //执行闭包
        composeBtnClouser?()
        
        //调用代理方法
        // ?  判断前面的对象是否为空
        lwDelegate?.composeBtnDidSelected()
        
        
    }
    
    //设置子控件位置
    override func layoutSubviews() {
        
        //一定要添加这句代码
        super.layoutSubviews()
        
        composeBtn.center.x = frame.size.width / 2
        
        composeBtn.center.y = frame.size.height / 2
        
        //计算每个按钮的宽度
        let itemWith = frame.size.width / 5
        
        
        //记录遍历到是第几个
        var indx = 0
        
        
        
        //获取系统按钮控件
        for value in subviews {
            
           //找到按钮
            if value.isKind(of: NSClassFromString("UITabBarButton")!) {
                
                value.frame.size.width = itemWith
                
                //设置系统按钮的X坐标
                value.frame.origin.x = CGFloat(indx) * itemWith
                
                indx += 1
                
                if indx == 2{
                    
                    indx += 1
                    
                }
                
            }
            
        }
        
        
        
    }
 

}
